<template>
  <div class="goods-list-container">
    <div class="page-header">
      <h2>商品管理</h2>
      <el-button type="primary" @click="openAddDialog">新增商品</el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-filter">
      <el-input
        v-model="searchForm.name"
        placeholder="请输入商品名称"
        style="width: 200px; margin-right: 10px;"
        clearable
      />
      <el-select
        v-model="searchForm.category_id"
        placeholder="请选择分类"
        style="width: 150px; margin-right: 10px;"
        clearable
      >
        <el-option
          v-for="category in categories"
          :key="category.id"
          :label="category.name"
          :value="category.id"
        />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 商品列表 -->
    <el-table :data="goodsList.records" style="width: 100%" v-loading="loading">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="商品ID" width="80" />
      <el-table-column label="商品图片" width="120">
        <template #default="scope">
          <img 
            v-if="scope.row.imgs" 
            :src="scope.row.imgs" 
            style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px;"
            :alt="scope.row.name"
          />
          <div v-else style="width: 80px; height: 80px; line-height: 80px; text-align: center; background-color: #f5f5f5; border-radius: 4px;">
            无图片
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" width="200" />
      <el-table-column prop="description" label="商品描述" :show-overflow-tooltip="true" />
      <el-table-column prop="discount" label="折扣" width="100" />
      <el-table-column prop="sales" label="销量" width="100" />
      <el-table-column prop="category_id" label="分类" width="120">
        <template #default="scope">
          {{ getCategoryName(scope.row.category_id) }}
        </template>
      </el-table-column>
      <el-table-column prop="recommend" label="是否推荐" width="120">
        <template #default="scope">
          <el-switch
            v-model="scope.row.recommend"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="handleRecommendChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="goodsList.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑商品对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="resetForm"
    >
      <el-form
        ref="goodsFormRef"
        :model="goodsForm"
        label-width="100px"
        style="max-width: 600px;"
      >
        <el-form-item label="商品名称" prop="name" :rules="[{ required: true, message: '请输入商品名称', trigger: 'blur' }]">
          <el-input v-model="goodsForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        
        <el-form-item label="商品描述" prop="description" :rules="[{ required: true, message: '请输入商品描述', trigger: 'blur' }]">
          <el-input v-model="goodsForm.description" type="textarea" placeholder="请输入商品描述" />
        </el-form-item>
        
        <el-form-item label="商品分类" prop="category_id" :rules="[{ required: true, message: '请选择商品分类', trigger: 'change' }]">
          <el-select v-model="goodsForm.category_id" placeholder="请选择商品分类">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="折扣" prop="discount">
          <el-input v-model="goodsForm.discount" placeholder="请输入折扣" />
        </el-form-item>
        
        <el-form-item label="是否推荐" prop="recommend">
          <el-switch
            v-model="goodsForm.recommend"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

// 表格数据
const goodsList = ref({ records: [], total: 0 });
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索表单
const searchForm = reactive({
  name: '',
  category_id: ''
});

// 分类数据
const categories = ref<Array<any>>([]);

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('新增商品');
const goodsFormRef = ref();
const goodsForm = reactive({
  id: null,
  name: '',
  description: '',
  discount: '',
  category_id: '',
  recommend: 0
});

// 加载商品列表
const loadGoodsList = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      name: searchForm.name || undefined,
      category_id: searchForm.category_id || undefined
    };
    const res = await axios.get('/api/good', { params });
    if (res.data.code === 200 && res.data.data) {
      goodsList.value = res.data.data;
    }
  } catch (error) {
    ElMessage.error('加载商品列表失败');
    console.error('加载商品列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 加载分类列表
const loadCategories = async () => {
  try {
    const res = await axios.get('/api/category/list');
    if (res.data.code === 200 && res.data.data) {
      categories.value = res.data.data;
    }
  } catch (error) {
    ElMessage.error('加载分类列表失败');
    console.error('加载分类列表失败:', error);
  }
};

// 获取分类名称
const getCategoryName = (categoryId: any) => {
  const category = categories.value.find(cat => cat.id === categoryId);
  return category ? category.name : '-';
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadGoodsList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.name = '';
  searchForm.category_id = '';
  currentPage.value = 1;
  loadGoodsList();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  loadGoodsList();
};

// 当前页变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  loadGoodsList();
};

// 打开新增对话框
const openAddDialog = () => {
  dialogTitle.value = '新增商品';
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = async (row: any) => {
  dialogTitle.value = '编辑商品';
  try {
    const res = await axios.get(`/api/good/${row.id}`);
    if (res.data.code === 200 && res.data.data) {
      Object.assign(goodsForm, res.data.data);
      dialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error('加载商品详情失败');
    console.error('加载商品详情失败:', error);
  }
};

// 重置表单
const resetForm = () => {
  goodsForm.id = null;
  goodsForm.name = '';
  goodsForm.description = '';
  goodsForm.discount = '';
  goodsForm.category_id = '';
  goodsForm.recommend = 0;
  if (goodsFormRef.value) {
    goodsFormRef.value.resetFields();
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!goodsFormRef.value) return;
  
  try {
    await goodsFormRef.value.validate();
    
    if (goodsForm.id) {
      // 编辑商品
      const res = await axios.put('/api/good', goodsForm);
      if (res.data.code === 200) {
        ElMessage.success('修改成功');
        dialogVisible.value = false;
        loadGoodsList();
      }
    } else {
      // 新增商品
      const res = await axios.post('/api/good', goodsForm);
      if (res.data.code === 200) {
        ElMessage.success('新增成功');
        dialogVisible.value = false;
        loadGoodsList();
      }
    }
  } catch (error) {
    console.error('提交表单失败:', error);
  }
};

// 删除商品
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const res = await axios.delete(`/api/good?idList=${id}`);
    if (res.data.code === 200) {
      ElMessage.success('删除成功');
      loadGoodsList();
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
      console.error('删除失败:', error);
    }
  }
};

// 推荐状态改变
const handleRecommendChange = async (row: any) => {
  try {
    await axios.put('/api/good', {
      id: row.id,
      recommend: row.recommend
    });
    ElMessage.success('修改成功');
  } catch (error) {
    // 恢复原来的值
    row.recommend = row.recommend === 1 ? 0 : 1;
    ElMessage.error('修改失败');
    console.error('修改推荐状态失败:', error);
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadCategories();
  loadGoodsList();
});
</script>

<style scoped>
.goods-list-container {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.search-filter {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>